<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>编辑销售退货订单</title>
<script type="text/javascript">
    Ext.onReady(function () {
        var version = Ext.create('Ext.form.field.Hidden', {
            name: 'lock_version'
        });

        var saleOrderId = Ext.create('Ext.form.field.Hidden', {
            name: 'id'
        });

        //备注
        var desc = Ext.create('Ext.form.field.Text', {
            fieldLabel: '备注',
            name: 'description',
            anchor: '97%'
        });

        //客户
        var customer = Ext.create('Ext.form.field.Text', {
            fieldLabel: '客户',
            allowBlank: false,
            readOnly: true,
            name: 'customer_name',
            anchor: '95%'
        });

        //要求退货时间
        var returnDate = Ext.create('Ext.form.field.Date', {
            fieldLabel: '退货日期',
            allowBlank: false,
            name: 'return_date',
            format: 'Y-m-d', //格式化日期
            //disabledDays: [0,6],	//不让选择周六，周日
            //disabledDaysText: "周末要休息",
            invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
            blankText: "要求退货日期必须选择",
            emptyText: '退货日期...'
            //anchor: '50%'
        });

        //合同号
        var contractNumber = Ext.create('Ext.form.field.Text', {
            fieldLabel: '合同编号',
            allowBlank: true,
            readOnly: true,
            name: 'contract_number',
            anchor: '90%'
        });

        //联系人
        var linkman = Ext.create('Ext.form.field.Text', {
            fieldLabel: '联系人',
            name: 'linkman',
            anchor: '95%',
            allowBlank: false
        });

        //联系电话
        var phone = Ext.create('Ext.form.field.Text', {
            fieldLabel: '联系电话',
            name: 'phone',
            anchor: '95%',
            allowBlank: false
        });

        var receiveAddress = Ext.create('Ext.form.field.Text', {
            fieldLabel: '地址',
            allowBlank: false,
            name: 'receive_address',
            anchor: '97%'
        });

        //总金额
        var sumAmount = Ext.create('Ext.form.field.Number', {
            fieldLabel: '总金额',
            name: "amount",
            readOnly: true,
            allowBlank: false,
            allowDecimals: true,
            minValue: 0,
            anchor: '90%'
        });

        var productCBB = Ext.create('Ext.form.ComboBox', {
            store: productAllInfoStore,
            emptyText: '请选择...',
            displayField: 'name',
            loadingText: '搜索中...',
            anchor: '100%',
            minChars: 0,
            listConfig: {
                loadingText: 'Searching...',
                getInnerTpl: function () {
                    return '<div style="float:left; width:200px" data-qtip="{name}">{name:ellipsis(18)}</div><div style="float:left; width:110px">{number}</div>{is_suit}';
                }
            },
            pageSize: 10
        });

        //select( Ext.form.field.Picker field, Mixed value, Object options )
        productCBB.on('select', function (field, record, options) {
            //var saleOrderItemRecord = saleOrderDetailSM.getSelected();
            var sm = saleReturnedDetailGrid.getSelectionModel();
            var records = sm.getSelection();
            var saleOrderItemRecord = records[0];
            //alert(saleOrderItemRecord);
            if (!saleOrderItemRecord) {
                return false;
            }
            if (isDuplicateByProduct(saleReturnedDetailDS, record[0].get('id'), saleOrderItemRecord.id)) {
                //删除当前记录
                saleReturnedDetailDS.remove(saleOrderItemRecord);
            } else {
                if (saleOrderItemRecord.get('product_id') != record[0].get('id')) {
                    saleOrderItemRecord.set('number', record[0].get('number'));
                    saleOrderItemRecord.set('spec', record[0].get('spec'));
                    saleOrderItemRecord.set('unit', record[0].get('unit'));
                    saleOrderItemRecord.set('quantity', 1);
                    saleOrderItemRecord.set('discount', 1);
                    saleOrderItemRecord.set('product_id', record[0].get('id'));
                    //判断套装
                    saleOrderItemRecord.set('is_suit', record[0].get('is_suit'));
                    //单价要特别拿出来处理,如果有销售类型的价格则使用，如果没有就使用销售类型的通用折扣。
                }
            }
            //从新计算得出总价。
            getSumAmount();
        });
        //--------------------------------------------------------------------------
        //销售订单列表Grid Store
        var saleReturnedDetailDS = Ext.create('Ext.data.Store', {
            autoDestroy: true,
            model: 'SaleReturnedDetailModel',
            proxy: {
                type: 'ajax',
                url: '/sale_returned/getSaleReturnedDetailsById',
                extraParams: {'sale_returned_id': <%=params[:id]%>},
                reader: {
                    type: 'json',
                    root: 'root',
                    totalProperty: 'totalProperty'// 数据集记录总数
                }
            },
            autoLoad: true
        });

        var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
            clicksToEdit: 1
        });

        //生成要订单的产品的Grid
        var saleReturnedDetailGrid = Ext.create('Ext.grid.Panel', {
            store: saleReturnedDetailDS,
            plugins: [cellEditing],
            columns: [Ext.create('Ext.grid.RowNumberer'), {
                header: 'id',
                dataIndex: 'id',
                width: 30
            }, {
                header: '产品名称',
                dataIndex: 'product_name',
                field: productCBB,
                width: 370
            }, {
                header: '产品ID',
                dataIndex: 'product_id',
                width: 50,
                hidden: false
            }, {
                header: '产品编号',
                dataIndex: 'number',
                width: 85
            }, {
                header: '规格',
                dataIndex: 'spec',
                width: 50
            }, {
                header: '单位',
                dataIndex: 'unit',
                width: 50
            }, {
                header: '数量',
                align: 'right',
                dataIndex: 'quantity',
                field: Ext.create('Ext.form.field.Number', {
                    allowBlank: false,
                    allowDecimals: false,
                    minValue: 1
                }),
                width: 50
            }, {
                header: '折扣',
                dataIndex: 'discount',
                renderer: Ext.util.Format.numberRenderer('0,000.000'),
                field: Ext.create('Ext.form.field.Number', {
                    allowBlank: false,
                    allowDecimals: true,
                    minValue: 0
                }),
                width: 45
            }, {
                header: '单价',
                dataIndex: 'unit_price',
                field: Ext.create('Ext.form.field.Number', {
                    allowBlank: false,
                    allowDecimals: false,
                    minValue: 0
                }),
                renderer: Ext.util.Format.numberRenderer('0,000.00'),
                align: 'right',
                width: 70
            }, {
                header: '金额',
                dataIndex: 'amount',
                align: 'right',
                renderer: Ext.util.Format.numberRenderer('0,000.00'),
                width: 90
            }, {
                header: '套装或单品',
                dataIndex: 'is_suit',
                width: 70
            }, {
                header: '备注',
                dataIndex: 'description',
                width: 80,
                field: Ext.create('Ext.form.field.Text', {
                    name: 'description',
                    anchor: '90%'
                })
            }],
            selModel: Ext.create('Ext.selection.CheckboxModel'),
            width: 1095,
            height: 290,
            tbar: [
                {
                    text: '添加产品',
                    iconCls: 'addItem',
                    handler: function () {
                        var record = Ext.ModelManager.create({
                            product_name: '请选择产品'
                        }, saleReturnedDetailGrid.getStore().model);
                        saleReturnedDetailDS.insert(0, record);
                    }
                },
                {
                    text: '删除',
                    iconCls: 'remove',
                    handler: function () {
                        var records = saleReturnedDetailGrid.getSelectionModel().getSelection();
                        cellEditing.cancelEdit();
                        saleReturnedDetailDS.remove(records);
                        getSumAmount();
                    }
                }
            ]
        });

        //暂时保存按钮
        var submitButton = Ext.create('Ext.Button', {
            text: '提交',
            tooltip: '提交销售退货订单。',
            iconCls: 'icon-save',
            handler: function () {
                if (saleReturnedFormPanel.form.isValid()) {
                    var productsJsonStr = gridStoreToJson(saleReturnedDetailDS, rejectKeyArray);
                    if (saleReturnedDetailDS.getCount() == 0 || productsJsonStr === "") {
                        Ext.MessageBox.show({
                            title: '提示',
                            msg: "您还没有选择有效的产品或选择的产品数量为0！",
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.INFO
                        });
                        return;
                    }
                    this.disable();
                    var allJsonStr = saleReturnedFormPanel.getForm().getValues();
                    allJsonStr = Ext.JSON.encode(allJsonStr);
                    allJsonStr = Ext.util.Format.substr(allJsonStr, 0, allJsonStr.length - 1);
                    allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
                    //alert(allJsonStr);
                    Ext.Ajax.request({
                        url: '/sale_returned/update',
                        success: function (result, request) {
                            //Ext.MessageBox.alert("提示","提交成功");
                            editSaleReturnedWin.destroy();
                        },
                        failure: function (result, request) {
                            Ext.MessageBox.show({
                                title: '消息',
                                msg: "通讯失败，请从新操作",
                                buttons: Ext.MessageBox.OK,
                                icon: Ext.MessageBox.WARNING
                            });
                            editSaleReturnedWin.destroy();
                        },
                        method: 'POST',
                        params: {
                            data: Ext.JSON.encode(allJsonStr),
                            authenticity_token: authToken.getValue()
                        }
                    });
                }
            }
        });

        //暂时保存按钮
        var closeButton = Ext.create('Ext.Button', {
            text: '关闭',
            tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
            iconCls: 'exit',
            handler: function () {
                editSaleReturnedWin.destroy();
            }
        });

        //采购申请的FormPanel
        var saleReturnedFormPanel = Ext.create('Ext.form.Panel', {
            fieldDefaults: {
                labelWidth: 55,
                labelAlign: 'right'
            },
            width: '1110',
            frame: true,
            url: '/sale_returned/update',
            method: 'GET',
            reader: Ext.create('Ext.data.reader.Json', {
                model: 'SaleReturnedModel',
                root: 'root'
            }),
            //defaultType: 'textfield',
            items: [
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: .4,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [customer]
                        },
                        {
                            columnWidth: .3,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [returnDate]
                        },
                        {
                            columnWidth: .3,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [contractNumber]
                        }
                    ]
                },
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: .4,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [linkman]
                        },
                        {
                            columnWidth: .6,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [phone]
                        }
                    ]
                },
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: 1,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [receiveAddress]
                        }
                    ]
                },
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: 1,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [desc]
                        }
                    ]
                },
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: 1,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [saleReturnedDetailGrid]
                        }
                    ]
                },
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: 0.3,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [sumAmount]
                        }
                    ]
                },
                saleOrderId,version
            ],
            buttons: [submitButton, closeButton]
        });

        saleReturnedFormPanel.form.load({
            url: '/sale_returned/getSaleReturnedById?id=' + <%=params[:id]%>,
            method: 'GET',
            waitMsg: '正在载入数据...',
            success: function (form, action) {
            },
            failure: function (form, action) {
                Ext.MessageBox.alert('提示信息', '信息加载失败');
            }
        });

        saleReturnedFormPanel.render('edit_sale_returned');
        //
        saleReturnedDetailGrid.on('edit', afterEdit, this);

        function afterEdit(editor, obj, options) {
            //
            if (obj.field == "quantity" || obj.field == "unit_price" || obj.field == "discount") {
                if (obj.record.get('quantity') > 0 && obj.record.get('unit_price') > 0) {
                    obj.record.set('amount', obj.record.get('quantity') * 100 * obj.record.get('unit_price') * 1000 * obj.record.get('discount') / 100000);
                } else {
                    obj.record.set('amount', 0);
                }
            }
            getSumAmount();
        }

        function getSumAmount() {
            sumAmount.setValue(0);
            var records = saleReturnedDetailDS.getRange(0, saleReturnedDetailDS.getCount());
            for (var i = 0; i < records.length; i++) {
                var record = records[i];
                var amount = record.get('amount');
                if (amount === undefined) {
                    amount = 0;
                }
                sumAmount.setValue(sumAmount.getValue() + Number(amount));
            }
        }
    })
</script>
</head>
<body>
<div id="edit_sale_returned"></div>
</body>
</html>